<template>
  <div>
    <el-dialog
      title="打印"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span v-if="printFinish == false">
        <div>模板</div>
        <div>
          <template-select
            :moduleCode="moduleCode"
            v-model="templateId"
          ></template-select></div
      ></span>
      <span slot="footer" class="dialog-footer" v-if="printFinish == false">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlePrint">确 定</el-button>
      </span>
      <div v-if="printFinish == true">
        <el-result icon="success" title="打印成功" subTitle="文件下载中...">
          <template slot="extra">
            <el-button
              type="primary"
              size="medium"
              @click="dialogVisible = false"
              >关闭</el-button
            >
          </template>
        </el-result>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import templateSelect from "@/components/Select/printTemplateSelect.vue";
import { printData } from "@/api/print";
import { downloadFile } from "@/api/file";
export default {
  components: {
    templateSelect,
  },
  data() {
    return {
      templateId: null,
      dialogVisible: false,
      printFinish: false,
    };
  },
  methods: {
    showDialog() {
      this.dialogVisible = true;
      this.printFinish = false;
    },
    handlePrint() {
      if (!this.templateId) return;

      let filter = JSON.stringify({
        ids: this.ids,
        pageIndex: 1,
        pageSize: 10000,
      });
      printData({
        moduleCode: this.moduleCode,
        templateId: this.templateId,
        filter: filter,
      }).then((res) => {
        if (!res) {
          this.$notify({
            title: "失败",
            message: "打印失败",
            type: "error",
            position: "bottom-right",
          });
          return;
        }
        this.printFinish = true;
        this.handleDownloadFile(res);
      });
    },
    handleDownloadFile(file) {
      let fileId = file.id;
      let name = file.fileName + file.fileExtension;
      let contentType = file.contentType;
      downloadFile({ id: fileId }).then((res) => {
        let blob = new Blob([res], {
          type: contentType,
        });
        let link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = name;
        link.click();

        window.URL.revokeObjectURL(link.href);

        this.dialogVisible = false;
      });
    },
    handleClose(){
      
    }
  },
  mounted() {},
  watch: {
    templateFileId: {
      handler(value) {
        this.$emit("change", value);
      },
    },
  },
  props: {
    moduleCode: {
      type: String,
    },
    ids: {
      type: Array,
      default: () => [],
    },
  },
};
</script>
<style scoped></style>
